package epam.bookShelf.actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import epam.bookShelf.bookStuff.BookBuilder;
import epam.bookShelf.database.BookDAO;
import epam.bookShelf.web.ServletListener;

/**
 * Servlet action for adding book via page "addBook.do"
 * @author Pustovit Michael, pustovitm@gmail.com
 */
public class AddBook extends Action {
	Logger log = Logger.getLogger(AddBook.class);
	
	@Override
	public void run(
			HttpServletRequest request, 
			HttpServletResponse response,
			ServletContext context) throws ServletException, IOException 
	{
		BookDAO dao = new BookDAO(ServletListener.getDAO());
        
        BookBuilder builder = new BookBuilder();        
        builder.setTitle(request.getParameterValues("title")[0]);
        
//        if ((request.getParameterValues("author")[0]).length() > 0) {
//        	builder.setAuthorName(request.getParameterValues("author")[0]);
//        }
        
        if ((request.getParameterValues("isbn")[0]).length() > 0) {
        	builder.setIsbn(Integer.valueOf(request.getParameterValues("isbn")[0]));
        }        
        
        if ((request.getParameterValues("description")[0]).length() > 0) {
        	builder.setDescription(request.getParameterValues("description")[0]);
        }
        
        try {			
        	dao.writeBook(builder.getBook());
        	log.info("Book writed to DB");
		} catch (SQLException e) {
			log.error("Error while book to DB writing");
			e.printStackTrace();
		}
        
    	
    	final PrintWriter w = response.getWriter();
        w.write("<html><body>");
        w.write("Book had been written into DB" + request.getRequestURL() + "<br/>");        
        w.write("</body></html>");
	}

}
